package com.kkui.liuxin.controller;

import com.alibaba.fastjson.JSONObject;
import com.kkui.liuxin.service.MkdirService;
import com.kkui.liuxin.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.lang.reflect.Field;

/**
 * @ClassName: Rename
 * @Description: rename file with folder
 * @author: kkui
 * @date: 2022/4/16 13:54
 * @status: 513
 */

@Slf4j
@Controller
@RequestMapping("/api")
public class Rename {

    @Resource
    UserService userService;
    @Resource
    MkdirService mkdirService;

    @ResponseBody
    @PostMapping("/rename")
    public String reName(@RequestBody String jsonString, @RequestHeader("Authorization") String authorization, HttpServletResponse response){
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        String path = jsonObject.getString("path");
        String newPath = jsonObject.getString("newPath");
        //文件夹不能包含的字符
        String[] banChr = {"\\", "/" , "," , "?" , "*" , "<" , ">" , ":" , "|"};

        File file = new File(mkdirService.getDefaultParentFolder() + userService.jwtGetUserId(authorization)
                + File.separator + path.replace("/",File.separator));
        File file1 = new File(mkdirService.getDefaultParentFolder() + userService.jwtGetUserId(authorization)
                + File.separator + newPath.replace("/",File.separator));

        if (file1.isDirectory()){
            for (String i : banChr){
                if (file1.getName().contains(i)){
                    response.setStatus(513);
                    return "文件名不合法";
                }
            }
        }
        if(file1.exists()){
            response.setStatus(513);
            return "同目录有同名";
        }

        if (file.renameTo(file1)) {
            return "重命名成功";
        }
        response.setStatus(513);
        return "重命名失败";

    }

}
